//
//  QSKVOObserver.swift
//  QSExtensions
//
//  Created by Song on 2019/5/23.
//  Copyright © 2019 Song. All rights reserved.
//

import UIKit

class QSKVOObserver: NSObject {
    private weak var target: AnyObject? = nil
    private var keyPath: String? = nil
    private var callback: ((Any) -> ())? = nil
    
    convenience init(targt: AnyObject, keyPath: String, options: NSKeyValueObservingOptions, callback: @escaping ((Any) -> ())) {
        self.init()
        
        self.target = targt
        self.keyPath = keyPath
        self.callback = callback
        
        self.target!.addObserver(self, forKeyPath: keyPath, options: options, context: nil)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        objc_sync_enter(self)
        if let changeValue = change {
            if let block = callback {
                block(changeValue[NSKeyValueChangeKey.newKey] as Any)
            }
        }
        objc_sync_exit(self)
    }
    
    /// 销毁
    func destroy() {
        if let tar = target, let kp = keyPath {
            tar.removeObserver(self, forKeyPath: kp, context: nil)
            target = nil
            keyPath = nil
            callback = nil
        }
    }
}
